package com.example.administrator.nurse.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/4/23.
 */
public class AutoTextView extends TextView{

    Paint mPaint;
    public AutoTextView(Context context) {
        this(context,null);
    }

    public AutoTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint=new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(getTextSize());
//        TypedArray typedArray=context.obtainStyledAttributes(attrs,);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint.FontMetrics fontMetrics=mPaint.getFontMetrics();
        String content=getText().toString();
        float baseline=fontMetrics.descent-fontMetrics.ascent;
        float x=0,y=baseline;
        Log.d("zzzzz", "MeasureWidth:" + getMeasuredWidth() + "  width:" + getWidth());
        Log.d("zzzzz", "left" + getLeft());
        int firstViewWidth=((ViewGroup)getRootView()).getChildAt(0).getMeasuredWidth();

        String[] contents=autoSqlit(mPaint,content,getMeasuredWidth()-400);
        Log.d("xxxxx",contents.toString());
        for(String context:contents){
            canvas.drawText(context, x, y, mPaint);
            Log.d("xxxxx",context);
            y+=baseline+fontMetrics.leading;
        }
    }
    private String[] autoSqlit(Paint paint,String content,float width){
        int length=content.length();
        float textWidth=paint.measureText(content);
        if(textWidth<width){
            return new String[]{content};
        }
        int start=0,end=1,i=0;
        int lines= (int) Math.ceil(textWidth/width);
        String[] contents=new String[lines];
        while(start<length){
            if(paint.measureText(content,start,end)>width){
                contents[i++]=content.subSequence(start,end).toString();
                start=end;
            }else if(end==length){
                contents[i]=content.subSequence(start,end).toString();
                break;
            }
            end++;
        }
        return contents;
    }
}
